package cn.edu.gzhu.workOrderManagement.intercepter;

import cn.edu.gzhu.workOrderManagement.enumeration.UserAuthorityEnum;
import cn.edu.gzhu.workOrderManagement.enumeration.WorkOrderProcessingStatusEnum;
import cn.edu.gzhu.workOrderManagement.mapper.UserMapper;
import cn.edu.gzhu.workOrderManagement.mapper.WorkOrderMapper;
import cn.edu.gzhu.workOrderManagement.pojo.entity.User;
import cn.edu.gzhu.workOrderManagement.service.TeamService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//总部负责人、总部商务、总部稽核查看所有工单
//分支机构只能查看本机构的工单
//小组成员能查看本小组的工单

//客户可以查看requestUser为自己的name的工单
@Component
@Slf4j
public class WorkOrderListInterceptor implements HandlerInterceptor {
    @Autowired
    TeamService teamService;
    @Autowired
    WorkOrderMapper workOrderMapper;
    @Autowired
    UserMapper userMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Claims claims =(Claims) request.getAttribute("claims");
        String username = claims.get("username").toString();
        String organization = claims.get("organization").toString();
        UserAuthorityEnum authority = UserAuthorityEnum.value2Object(claims.get("authority").toString());

        //总部负责人、总部商务、总部稽核查看所有工单
        if (UserAuthorityEnum.HEAD_BUSINESS.equals(authority)
                ||UserAuthorityEnum.HEAD_LEADER.equals(authority)
                ||UserAuthorityEnum.HEAD_AUDITORS.equals(authority)) {
            return true;
        }
        User opUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        String branchName = request.getParameter("branchName");
        String teamMember = request.getParameter("teamMember");
        Boolean isReassignment = Boolean.parseBoolean(request.getParameter("isReassignment"));
        //客户可以查看自己申请的
        if (opUser.getName().equals(request.getParameter("requestUser"))){
            return true;
        }
        //分公司主管及以上可查看分公司所有工单
        if (organization.equals(branchName)&&authority.getAuthority()>=3){
            return true;
        }
        //可以查看teamMember为自己且流转到自己的工单
        if (username.equals(teamMember)&&Boolean.TRUE.equals(isReassignment)){
            return true;
        }
        return false;

    }


}
